package com.jz.nacos.consumer.config;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.jz.commom.api.dto.request.Payment;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Properties;

@Data
@Component
@RefreshScope // 自动刷新配置
public class NacosConfig implements CommandLineRunner {

    // 自动刷新配置 todo @NacosValue还不行，应该是哪里配置不对
//    @NacosValue(value = "${myfrom}",autoRefreshed = true)
//    @Value("${myfrom}")
    private String myfrom;

    //    @NacosValue(value = "${nacostype2}",autoRefreshed = true)
//    @Value("${yourname2}")
    private String yourname2;

//    @Value("${myappname}")
    private String myappname;

    //    @Value("${payment}")
    private Payment payment;

    //    @Value("${payment2}")
    private Payment payment2;


    @Resource
    private NacosConfigProperties nacosConfigProperties;

    @Override
    public void run(String... args) throws Exception {
        // 上面的注解已经可以刷新配置了 这里就不用了
//        listenNacosProperties();
    }

    /**
     * 监听nacos配置刷新
     * 需要手动设置 刷新的值
     * @throws NacosException
     */
    private void listenNacosProperties() throws NacosException {
        String nacos_host = nacosConfigProperties.getServerAddr();
        String group = nacosConfigProperties.getGroup();
        Properties properties = new Properties();
        properties.put("serverAddr",nacos_host);
        properties.put("username",nacosConfigProperties.getUsername());
        properties.put("password",nacosConfigProperties.getPassword());
        properties.put("refreshEnabled",nacosConfigProperties.isRefreshEnabled());
        ConfigService configService = NacosFactory.createConfigService(properties);
        nacosConfigProperties.getSharedConfigs().forEach(item->{
            try {
                String content = configService.getConfig(item.getDataId(),group,1000);
                System.out.println(item.getDataId());
                System.out.println(content);
                // 这里手动刷新新值
            } catch (NacosException e) {
                e.printStackTrace();
            }
        });
        nacosConfigProperties.getExtensionConfigs().forEach(item->{
            try {
                String content = configService.getConfig(item.getDataId(),group,10000);
                System.out.println(item.getDataId());
                System.out.println(content);
                // 这里手动刷新新值
            } catch (NacosException e) {
                e.printStackTrace();
            }
        });
    }

}
